import { Component } from '@angular/core';
import { NavController, NavParams, LoadingController, Events, ToastController, Platform } from 'ionic-angular';
import { DeviceProvider } from '../../../providers/service/device'
import { AnalysisProvider } from '../../../providers/service/analysis'
import echarts from 'echarts';
import { Observable } from "rxjs/Rx";
import { DEFINE } from "../../../providers/Constants";
import { GpsUtil } from "../../../util/gpsConvert";
import { DeviceWhPage } from '../device-wh/device-wh'


/**
 * Generated class for the DeviceDetailPage page.
 *
 * See https://ionicframework.com/docs/components/#navigation for more info on
 * Ionic pages and navigation.
 */

@Component({
    selector: 'page-device-detail',
    templateUrl: 'device-detail.html',
})
export class DeviceDetailPage {

    constructor(public navCtrl: NavController,
        public loadingCtrl: LoadingController,
        public toast: ToastController,
        public events: Events,
        public deviceProvider: DeviceProvider,
        public analysisProvider: AnalysisProvider,
        public platform: Platform,
        public navParams: NavParams) {    
    }


    //存在操作后，不保存 数据不一致的问题，后续需改进
    baseUrl = DEFINE.baseURL + '/getFile/';
    isReady = false;
    isLoading = true;
    isError = false;
    id: any;        //设备ID
    type = '0'; //0基本 1详细 2曲线 3设备操作

    analysisType = 'week';        //曲线图的类型

    status = '1';
    devObj: any;

    //操作参数
    actionParam = {
        checkedTimes: [],
        status: 3,
        fanFlag: 0,
        lampFlag: 0,
        runMinutes: 1,
        voltageThreshold: '240',
        voltageThresholdFlag: true
    }

    //时间段数据源
    timeArr = [
        { start: '00:00', end: '01:00' },
        { start: '01:00', end: '02:00' },
        { start: '02:00', end: '03:00' },
        { start: '03:00', end: '04:00' },
        { start: '04:00', end: '05:00' },
        { start: '05:00', end: '06:00' },
        { start: '06:00', end: '07:00' },
        { start: '07:00', end: '08:00' },
        { start: '08:00', end: '09:00' },
        { start: '09:00', end: '10:00' },
        { start: '10:00', end: '11:00' },
        { start: '11:00', end: '12:00' },
        { start: '12:00', end: '13:00' },
        { start: '13:00', end: '14:00' },
        { start: '14:00', end: '15:00' },
        { start: '15:00', end: '16:00' },
        { start: '16:00', end: '17:00' },
        { start: '17:00', end: '18:00' },
        { start: '18:00', end: '19:00' },
        { start: '19:00', end: '20:00' },
        { start: '20:00', end: '21:00' },
        { start: '21:00', end: '22:00' },
        { start: '22:00', end: '23:00' },
        { start: '23:00', end: '24:00' }
    ]

    ionViewDidLoad() {
        this.id = this.navParams.data.id;
        this.isReady = true;
        this.isLoading = true;
        this.devObj = null;

        this.deviceProvider.getDetail(this.id).then((res: any) => {
            console.log(res);
            this.devObj = res;
            // this.devObj['timeArr'] = this.encodeRunDuration();        //选中的时间段
            this.isLoading = false;

            this.actionParam.checkedTimes = this.encodeRunDuration();
            this.actionParam.status = res.status;
            this.actionParam.fanFlag = res.fanFlag;
            this.actionParam.lampFlag = res.lampFlag;
            this.actionParam.runMinutes = res.runMinutes || 240;
            this.actionParam.voltageThreshold = res.voltageThreshold || '';
            if (this.actionParam.voltageThreshold) {
                this.actionParam.voltageThresholdFlag = true;
            } else {
                this.actionParam.voltageThresholdFlag = false;
            }

        }, err => {
            this.isError = true;
            this.isLoading = false;
        })
        console.log('ionViewDidLoad DeviceDetailPage');
    }

    //返回[{start:xxx},{start:xxx}]
    encodeRunDuration() {
        var d = [];
        let arr = this.devObj.runDuration;
        if (!arr) {
            return [];
        } else {
            arr = eval("(" + arr + ")")
        }
        for (var i = 0; i < arr.length; i++) {
            d.push(arr[i].start);
        }
        return d;
    }

    //返回 [{"start":"01:00","end":"02:00"},{"start":"02:00","end":"03:00"}]
    decodeRunDuration() {
        var d = [];
        this.actionParam['checkedTimes'].map((v) => {
            let _start = v;
            let _end: any = parseInt(v.substr(0, 2)) + 1;
            if (_end < 10) {
                _end = "0" + _end + ':00';
            } else {
                _end = _end + ':00';
            }
            d.push({ start: _start, end: _end });
        });
        return d;
    }

    //监听改变tab为曲线图时 需要初始化一下
    segmentChanged(e) {
        if (this.type == '2') {
            this.refreshDiagram();
        }
        //console.log(this.type);
    }

    //改变曲线图粒度
    changeAnalysisType(type) {
        if (type == this.analysisType) {
            return;
        }
        if (type == 'week') {
            this.analysisType = 'week';
        } else if (type == 'month') {
            this.analysisType = 'month';
        } else if (type == 'year') {
            this.analysisType = 'year';
        }

        this.refreshDiagram();

    }

    //刷新视图
    refreshDiagram() {
        let observableBatch = [this.getTemperaturePromise1(), this.getHumidity(), this.getBugRate()];

        let loading = this.loadingCtrl.create({
            content: '正在获取最新数据'
        });
        loading.present();
        Observable.forkJoin(observableBatch).subscribe((res: any) => {
            // console.log(res);
            loading.dismiss();
            setTimeout(() => {
                res.map((v, idx) => {
                    console.log(v);
                    var myChart = echarts.init(document.getElementById('ec-line' + idx));
                    myChart.setOption(this.getLineOption(v), 0);
                })
            }, 0);
        });
    }


    //获取温度
    getTemperaturePromise1() {
        let obj = { "timeScale": this.analysisType, "deviceId": this.id };
        return this.analysisProvider.getTemperature(obj);
    }

    //获取虫量
    getBugRate() {
        let obj = { "timeScale": this.analysisType, "deviceId": this.id };
        return this.analysisProvider.getBugRate(obj);
    }

    //湿度
    getHumidity() {
        let obj = { "timeScale": this.analysisType, "deviceId": this.id };
        return this.analysisProvider.getHumidity(obj);
    }

    //获取折线图Option
    getLineOption(obj) {
        if (obj.seriesData) {
            obj.seriesData.map((v, idx) => {
                if (v != '-') {
                    obj.seriesData[idx] = parseFloat(obj.seriesData[idx]).toFixed(2)
                }
            })
        }
        let option = {
            color: ['#29c3ac'],
            title: {
                text: obj.title,
                textStyle: {
                    fontSize: '16px'
                }
            },
            tooltip: {
                trigger: 'axis'
            },
            xAxis: {
                type: 'category',
                splitLine: {
                    show: false
                },
                data: obj.xAxisData || []
            },
            yAxis: {
                type: 'value',
                splitLine: {
                    show: false
                },
                axisLabel: {
                    formatter: '{value}'
                }
            },
            series: [
                {
                    name: '值',
                    type: 'line',
                    data: obj.seriesData || [],
                    smooth: true,
                    markPoint: {
                        data: [
                            { type: 'max', name: '最大值' },
                            { type: 'min', name: '最小值' }
                        ]
                    },
                    markLine: {
                        data: [
                            { type: 'average', name: '平均值' }
                        ]
                    }
                }
            ]
        };
        return option;

    }


    //更新设备一些状态
    updateStatus() {
        //反编译时间段
        // 光控模式
        // runMinutes 工作时长 分钟
        // voltageThreshold 电压阈值

        let obj = {
            id: this.id,
            status: this.actionParam.status,
            lampFlag: this.actionParam.lampFlag ? 1 : 0,
            fanFlag: this.actionParam.fanFlag ? 1 : 0,
            runMinutes: this.actionParam.runMinutes || '240',
            voltageThreshold: (() => {
                if (!this.actionParam.voltageThresholdFlag) {
                    return 0;
                } else {
                    return this.actionParam.voltageThreshold;
                }
            })(),
            runDuration: this.decodeRunDuration()
        };
        console.log(obj.status)
        if (obj.status == 0) {
            let toast = this.toast.create({
                message: '请选择模式',
                duration: 2000,
                position: 'bottom'
            });
            toast.present();
            return;
        }

        let loading = this.loadingCtrl.create({
            content: '正在下发状态变更指令'
        });
        loading.present();
        this.deviceProvider.updateStatus(obj).then((res) => {
            loading.setContent("操作成功，将在未来几分钟内进行变更");
            setTimeout(() => {
                loading.dismiss();
            }, 3000);
        }, err => {
            loading.dismiss();
            console.log(err);
        })
    }

    //下达GPS更新指令
    updateGPS() {
        let loading = this.loadingCtrl.create({
            content: '正在下发指令，请稍等'
        });
        loading.present();
        this.deviceProvider.updateGPS(this.id).then(res => {
            loading.setContent("下发成功");
            setTimeout(() => {
                loading.dismiss();
            }, 500);
        }, err => {
            loading.setContent("抱歉，下发失败");
            setTimeout(() => {
                loading.dismiss();
            }, 1000);
        })
    }

    //导航到对应地方
    guideAddress() {
        var _name = this.devObj.name || '未知名称';
        var _address = this.devObj.provinceName + this.devObj.districtName + this.devObj.address + '('+ this.devObj.farmName + ')';
        var _gpsObj =  GpsUtil.bd_encrypt(this.devObj.latitude, this.devObj.longitude);
        var _longitude = _gpsObj.lon;
        var _latitude = _gpsObj.lat;

        var _urlLink = 'location='+ _latitude +','+ _longitude +'&title='+ _name +'&content='+ _address +'&src=webapp.marker.answ.zhny';

        if (this.platform.is('ios')) {
            window.location.href = 'baidumap://map/marker?' + _urlLink
        }
        else if (this.platform.is('android')) {
            window.location.href = 'bdapp://map/marker?' + _urlLink;
        }

    }

    //维护
    pToDeviceUpdate(){
        let _this = this;
        this.navCtrl.push(DeviceWhPage, { type: '2', id: _this.id });     //1  添加设备  2维护设备

    }

}
